<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="新闻标题" prop="newsTitle">
        <el-input
          v-model="queryParams.newsTitle"
          placeholder="请输入新闻标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="副标题" prop="subtitle">
        <el-input
          v-model="queryParams.subtitle"
          placeholder="请输入副标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布日期" prop="publishDate">
        <el-date-picker
          clearable
          v-model="queryParams.publishDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择发布日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="新闻类别" prop="newsCategory">
        <el-select
          v-model="queryParams.newsCategory"
          placeholder="请选择新闻类别"
          clearable
        >
          <el-option
            v-for="dict in dict.type.news_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:news:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:news:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:news:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:news:export']"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleSyncToEs"
          >同步到ES</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="newsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="新闻id" align="center" prop="newsId" />
      <el-table-column label="新闻标题" align="center" prop="newsTitle" />
      <el-table-column label="副标题" align="center" prop="subtitle" />
      <el-table-column
        label="封面图"
        align="center"
        prop="coverImageUrl"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview
            :src="scope.row.coverImageUrl"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="新闻内容" align="center" prop="newsContent">
        <template slot-scope="scope">
          <div class="ellipsis" @click="handleView(scope.row)">
            <!--            {{ scope.row.newsContent | truncate(5) }} &lt;!&ndash; 显示前5个字 &ndash;&gt;-->
            {{ scope.row.newsContent.slice(0, 3) + "..." }}
            <!-- 显示前3字 -->
          </div>
        </template>
      </el-table-column>

      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column
        label="发布日期"
        align="center"
        prop="publishDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="新闻类别" align="center" prop="newsCategory">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.news_category"
            :value="scope.row.newsCategory"
          />
        </template>
      </el-table-column>
      <el-table-column label="浏览次数" align="center" prop="viewCount" />
      <el-table-column
        label="发布时间"
        align="center"
        prop="publishTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:news:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:news:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新闻详情对话框 -->
    <el-dialog
      :title="viewTitle"
      :visible.sync="viewOpen"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <!-- 新闻详情内容区域 -->
      <div class="news-detail-container">
        <!-- 标题区域 -->
        <div class="news-title">
          {{ viewForm.newsTitle }}
        </div>

        <!-- 副标题区域 -->
        <div class="news-subtitle" v-if="viewForm.subtitle">
          {{ viewForm.subtitle }}
        </div>

        <!-- 元信息区域（作者、发布时间） -->
        <div class="news-meta">
          <span class="meta-item">作者：{{ viewForm.author || '未知' }}</span>
          <span class="meta-item">发布时间：{{ viewForm.publishDate || '暂无' }}</span>
        </div>

        <!-- 内容分隔线 -->
        <div class="news-divider"></div>

        <!-- 正文内容区域 -->
        <div class="news-content">
          <!-- 支持HTML格式的内容展示（若后端返回带标签的富文本） -->
          <div v-html="viewForm.newsContent"></div>

          <!-- 若为纯文本内容，可直接使用插值 -->
          <!-- {{ viewForm.newsContent }} -->
        </div>
      </div>

      <!-- 底部按钮 -->
      <div
        slot="footer"
        class="dialog-footer"
        style="
      display: flex;
      justify-content: flex-end;
      padding: 20px;
      border-top: 1px solid #f0f2f5;
    "
      >
        <el-button
          type="primary"
          @click="newsDetailClose"
          style="padding: 8px 24px; font-weight: 500"
        >
          关闭
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改新闻资讯对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="新闻标题" prop="newsTitle">
          <el-input v-model="form.newsTitle" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="form.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="封面图url" prop="coverImageUrl">
          <image-upload v-model="form.coverImageUrl" />
        </el-form-item>
        <el-form-item label="新闻内容">
          <editor v-model="form.newsContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="新闻类别" prop="newsCategory">
          <el-select v-model="form.newsCategory" placeholder="请选择新闻类别">
            <el-option
              v-for="dict in dict.type.news_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            clearable
            v-model="form.publishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发布时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listNews,
  getNews,
  delNews,
  addNews,
  updateNews,
  updateNewsToEs,
} from "@/api/lawyer_aid/news";

export default {
  name: "News",
  dicts: ["news_category", "is_published", "is_top"],
  data() {
    return {
      // 新增详情对话框数据
      viewOpen: false,
      viewTitle: "新闻详情",
      viewForm: {},

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 新闻资讯表格数据
      newsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        newsTitle: null,
        subtitle: null,
        author: null,
        publishDate: null,
        newsCategory: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        newsTitle: [
          { required: true, message: "新闻标题不能为空", trigger: "blur" },
        ],
        newsContent: [
          { required: true, message: "新闻内容不能为空", trigger: "blur" },
        ],
        newsCategory: [
          {
            required: true,
            message:
              "新闻类别'1业内资讯','2法律速递','3企业新闻','4视频'不能为空",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询新闻资讯列表 */
    getList() {
      this.loading = true;
      listNews(this.queryParams).then((response) => {
        this.newsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    newsDetailsReset(){
      this.viewForm = {
        newsTitle: null,
        subtitle: null,
        newsContent: null,
        author: null,
        publishDate: null
      };
      this.resetForm("viewForm");

    },
    // 表单重置
    reset() {
      this.form = {
        newsId: null,
        newsTitle: null,
        subtitle: null,
        coverImageUrl: null,
        newsContent: null,
        author: null,
        publishDate: null,
        isPublished: null,
        newsCategory: null,
        viewCount: null,
        isTop: null,
        publishTime: null,
        createdTime: null,
        createdBy: null,
        updatedBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.newsId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加新闻资讯";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const newsId = row.newsId;
      getNews(newsId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改新闻资讯";
      });
    },

    // 查看详情方法（优化后通过接口获取数据）
    handleView(row) {
      const newsId = row.newsId;
      this.viewOpen = true;
      this.loading = true; // 显示加载状态

      // 调用详情接口
      getNews(newsId)
        .then((response) => {
          this.viewForm = response.data; // 赋值详情数据
          this.loading = false; // 隐藏加载状态
        })
        .catch((error) => {
          this.$modal.msgError("获取新闻详情失败");
          this.viewOpen = false;
        });
    },

    // 关闭详情弹窗
    newsDetailClose() {
      this.viewOpen = false;
      this.newsDetailsReset();
    },



    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.newsId != null) {
            updateNews(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNews(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const newsIds = row.newsId || this.ids;
      this.$modal
        .confirm('是否确认删除新闻资讯编号为"' + newsIds + '"的数据项？')
        .then(function () {
          return delNews(newsIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/news/export",
        {
          ...this.queryParams,
        },
        `news_${new Date().getTime()}.xlsx`
      );
    },
    handleSyncToEs() {
      this.$modal.confirm("确定要将所有新闻同步到ES吗？").then(() => {
        this.loading = true;
        updateNewsToEs()
          .then((res) => {
            this.loading = false;
            if (res.code === 200) {
              this.$modal.msgSuccess("同步成功");
            } else {
              this.$modal.msgError(res.msg || "同步失败");
            }
          })
          .catch(() => {
            this.loading = false;
            this.$modal.msgError("同步失败");
          });
      });
    },
  },
};
</script>

<style scoped>
.news-detail-container {
  padding: 10px 20px;
}

.news-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.5;
}

.news-subtitle {
  font-size: 16px;
  color: #666;
  margin-bottom: 16px;
  font-style: italic;
}

.news-meta {
  display: flex;
  gap: 20px;
  color: #888;
  font-size: 14px;
  margin-bottom: 16px;
  padding-bottom: 8px;
}

.news-divider {
  height: 1px;
  background-color: #f0f2f5;
  margin: 16px 0;
}

.news-content {
  font-size: 15px;
  color: #333;
  line-height: 1.8;
  padding: 10px 0;
  min-height: 200px; /* 避免内容过短时布局失衡 */
}

</style>
